// pages/main/pending-submit/pending-submit.js
Page({
  data: {
    type: 'receive', // receive: 收款, payment: 付款, refund: 退款
    typeText: '收款',
    appId: null,
    appName: '',
    categoryId: null,
    subCategoryId: null,
    searchKeyword: '',
    dataList: [],
    selectedItems: [],
    isAllSelected: false,
    loading: true,
    total: 0,
    totalAmount: '0.00',
    showDetailModal: false,
    currentDetail: null
  },

  onLoad(options) {
    console.log('待提交页面参数:', options);
    
    // 初始化长按触发标志
    this.longPressTriggered = false;
    
    const type = options.type || 'receive';
    const typeTextMap = {
      'receive': '收款',
      'payment': '付款',
      'refund': '退款'
    };
    
    this.setData({
      type: type,
      typeText: typeTextMap[type] || '收款',
      appId: options.appId || null,
      appName: options.appName ? decodeURIComponent(options.appName) : '',
      categoryId: options.categoryId || null,
      subCategoryId: options.subCategoryId || null
    });
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: options.subCategoryName ? decodeURIComponent(options.subCategoryName) : '待提交'
    });
    
    // 加载数据
    this.loadData();
  },

  // 加载数据
  loadData() {
    this.setData({ loading: true });
    
    wx.request({
      url: `${getApp().globalData.serverUrl}/GetPendingSubmitList/`,
      method: 'POST',
      data: {
        type: this.data.type,
        app_id: this.data.appId,
        category_id: this.data.categoryId,
        sub_category_id: this.data.subCategoryId,
        search: this.data.searchKeyword,
        page: 1,
        page_size: 1000  // 加载所有数据
      },
      success: (res) => {
        if (res.data.status) {
          const data = res.data.data || [];
          // 为每个数据项添加selected属性
          data.forEach(item => {
            item.selected = false;
          });
          
          const total = res.data.total || 0;
          const totalAmount = res.data.total_amount || '0.00';
          
          this.setData({
            dataList: data,
            total: total,
            totalAmount: totalAmount,
            loading: false
          });
          
          // 更新全选状态
          this.updateSelectAllStatus();
        } else {
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('获取数据失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 刷新
  onRefresh() {
    this.setData({
      selectedItems: [],
      isAllSelected: false
    });
    this.loadData();
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm() {
    this.setData({
      selectedItems: [],
      isAllSelected: false
    });
    this.loadData();
  },

  // 全选/取消全选
  onSelectAll(e) {
    const checked = e.detail.value.length > 0;
    const dataList = this.data.dataList.map(item => {
      item.selected = checked;
      return item;
    });
    
    this.setData({
      dataList: dataList,
      isAllSelected: checked,
      selectedItems: checked ? dataList.map(item => item.orderNumber) : []
    });
  },

  // 选择单个项目
  onSelectItem(e) {
    const index = e.currentTarget.dataset.index;
    const checked = e.detail.value.length > 0;
    const dataList = this.data.dataList;
    dataList[index].selected = checked;
    
    // 更新选中项列表
    const selectedItems = [];
    dataList.forEach(item => {
      if (item.selected) {
        selectedItems.push(item.orderNumber);
      }
    });
    
    this.setData({
      dataList: dataList,
      selectedItems: selectedItems
    });
    
    // 更新全选状态
    this.updateSelectAllStatus();
  },

  // 点击行
  onRowTap(e) {
    // 如果触发了长按事件，不执行点击事件
    if (this.longPressTriggered) {
      this.longPressTriggered = false;
      return;
    }
    
    const index = e.currentTarget.dataset.index;
    const dataList = this.data.dataList;
    dataList[index].selected = !dataList[index].selected;
    
    // 更新选中项列表
    const selectedItems = [];
    dataList.forEach(item => {
      if (item.selected) {
        selectedItems.push(item.orderNumber);
      }
    });
    
    this.setData({
      dataList: dataList,
      selectedItems: selectedItems
    });
    
    // 更新全选状态
    this.updateSelectAllStatus();
  },

  // 长按行查看详情
  onRowLongPress(e) {
    this.longPressTriggered = true;
    const item = e.currentTarget.dataset.item;
    
    this.setData({
      currentDetail: item,
      showDetailModal: true
    });
    
    // 震动反馈
    wx.vibrateShort({
      success: function () {
        console.log('振动成功');
      },
      fail: function (err) {
        console.error('振动失败', err);
      }
    });
  },

  // 关闭详情弹窗
  onCloseDetailModal() {
    this.setData({
      showDetailModal: false,
      currentDetail: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 阻止遮罩层的触摸移动事件，防止背景页面滚动
  preventTouchMove() {
    // 空函数，用于阻止触摸移动事件
  },

  // 更新全选状态
  updateSelectAllStatus() {
    const allSelected = this.data.dataList.length > 0 && 
                        this.data.dataList.every(item => item.selected);
    this.setData({
      isAllSelected: allSelected
    });
  },

  // 批量提交
  onBatchSubmit() {
    if (this.data.selectedItems.length === 0) {
      wx.showToast({
        title: '请至少选择一项',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认提交',
      content: `确定要提交选中的 ${this.data.selectedItems.length} 项吗？`,
      success: (res) => {
        if (res.confirm) {
          this.submitData();
        }
      }
    });
  },

  // 提交数据
  submitData() {
    wx.showLoading({
      title: '提交中...'
    });
    
    wx.request({
      url: `${getApp().globalData.serverUrl}/BatchSubmitPending/`,
      method: 'POST',
      data: {
        type: this.data.type,
        app_id: this.data.appId,
        order_numbers: this.data.selectedItems
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          // 清空选中项并刷新数据
          this.setData({
            selectedItems: [],
            isAllSelected: false
          });
          this.loadData();
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('提交失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 导出
  onExport() {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none'
    });
  },

  // 排序
  onSort(e) {
    const key = e.currentTarget.dataset.key;
    // 排序功能可以在这里实现
    console.log('排序:', key);
  }
});

